﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using BUS;
using Entity;
using Share;

namespace SLMNG
{
    public partial class M_Invoices : BaseForm
    {
        dsCatalogue.InvoiceDetailsDataTable dt = new dsCatalogue.InvoiceDetailsDataTable();

        #region Constructor and form event

        public M_Invoices()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
            GridFormat();
            btnGetNextNumber.Enabled = false;
            cmbTable.EditValueChanged += cmbTable_EditValueChanged;
            StatusOfForm = FormStatus.Add;
        }               

        void Form1_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            string[] arg = new string[] { "ZoneCode","TableCode" };
            object[] obj = new object[] { DBNull.Value, DBNull.Value };
            DataSet ds1 = CatalogueBase.GetData(Table.STORE_SELECT, arg, obj);
            cmbTable.Properties.DataSource = ds1.Tables[0];
        }

        void cmbTable_EditValueChanged(object sender, EventArgs e)
        {
            txtCode.Text = string.Empty;

            string[] arg = new string[] { "TableCode", "Time" };
            object[] obj = new object[] { cmbTable.EditValue.ToString(), DateTime.Now };
            DataTable dtResult = CatalogueBase.GetData(InvoiceDTO.STORE_SELECT_TABLE_AT_CURRENT_TIME, arg, obj).Tables[0];

            if (dtResult.Rows.Count > 0)
            {
                btnGetNextNumber.Enabled = false;
                txtCode.Text = dtResult.Rows[0]["InvoiceCode"].ToString();
                dtpTimeUp.Enabled = false;
                StatusOfForm = FormStatus.Edit;
            }
            else
            {
                btnGetNextNumber.Enabled = true;
                StatusOfForm = FormStatus.Add;
                dtpTimeUp.Enabled = true;
            }
        }

        void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Name.Equals("Quantity"))
            {
                decimal unitCost = Global.decimalParse(gridView1.GetRowCellValue(e.RowHandle, "UnitCost"));
                decimal quantity = Global.decimalParse(gridView1.GetRowCellValue(e.RowHandle, "Quantity"));
                gridView1.SetRowCellValue(e.RowHandle, "Amount", unitCost * quantity);
            }
        }

        private void GridFormat()
        {
            gridView.DataSource = dt;
            gridView1.Columns["UnitCost"].DisplayFormat.FormatString = Global.CurrencyFormat;
            gridView1.Columns["UnitCost"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridView1.Columns["Amount"].DisplayFormat.FormatString = Global.CurrencyFormat;
            gridView1.Columns["Amount"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridView1.Columns["Quantity"].DisplayFormat.FormatString = Global.FORMAT_NUMBER;
            gridView1.Columns["Quantity"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridView1.CellValueChanged += gridView1_CellValueChanged;
        }

        #endregion

        #region Overrides Methods

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //if (txtCode.Text.Trim().Equals(string.Empty))
            //{
            //    Global.ShowMessageBox("Chưa có mã phiếu !", this.Text);
            //    return;
            //}

            string codeList = string.Empty;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                codeList += gridView1.GetRowCellValue(i, "ItemCode").ToString() + ",";
            }

            if (codeList.EndsWith(","))
                codeList = codeList.Remove(codeList.Length - 1, 1);

            DlgSelectFoods dlg = new DlgSelectFoods(codeList);
            dlg.ShowDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                DataTable dt1 = dlg.dtResult;
                dt1.Columns.Add("InvoiceCode", typeof(string));
                dt1.Columns["Cost"].ColumnName = "UnitCost";

                foreach (DataRow dr in dt1.Rows)
                {
                    dr["InvoiceCode"] = txtCode.Text;
                }
                foreach (DataRow item in dt1.Rows)
                {
                    dt.ImportRow(item);
                }
            }            
        }


        public override void fncInsert()
        {
            
        }

        public override void fncSave()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                MessageBox.Show(temp.ID_IS_NOT_NULL);
                return;
            }
            else if (gridView1.RowCount <= 0)
            {
                MessageBox.Show("Lưới phải có ít nhất 1 dòng!");
                return;
            }

            DataSet ds = new DataSet();

            decimal totalAmount = 0;

            DataTable dt2 = dt.Copy();
            dt2.TableName = "InvoiceDetail";
            dt2.Columns.Remove("ItemName");
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                decimal amount = Global.decimalParse(dt2.Rows[i]["Amount"]);
                if (amount <= 0)
                {
                    dt2.Rows.RemoveAt(i);
                    i--;
                }
                else
                    totalAmount += amount;
            }

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("InvoiceCode", typeof(string));
            dt1.Columns.Add("InvoiceDate", typeof(DateTime));
            dt1.Columns.Add("TableCode", typeof(string));
            dt1.Columns.Add("EmployeeCode", typeof(string));
            dt1.Columns.Add("CreatedBy", typeof(string));
            dt1.Columns.Add("TimeUp", typeof(DateTime));
            dt1.Columns.Add("TotalAmount", typeof(decimal));

            DataRow dr = dt1.NewRow();
            dr["InvoiceCode"] = txtCode.Text.Trim();
            dr["InvoiceDate"] = DateTime.Now;
            dr["TableCode"] = cmbTable.EditValue.ToString();
            dr["TotalAmount"] = totalAmount;
            dr["CreatedBy"] = Global.UserID;
            dr["EmployeeCode"] = DBNull.Value;
            dr["TimeUp"] = dtpTimeUp.EditValue;
            dt1.Rows.Add(dr);

            ds.Tables.Add(dt1);            
            ds.Tables.Add(dt2);

            string result = string.Empty;
            if (StatusOfForm == FormStatus.Add)
            {
                string[] arg = new string[] { InvoiceDTO.STORE_INSERT, InvoiceDetail.STORE_INSERT };
                result = CatalogueBase.SaveData(arg, ds);
            }
            else if(StatusOfForm == FormStatus.Edit)
            {
                string[] arg = new string[] { InvoiceDTO.STORE_UPDATE, InvoiceDetail.STORE_INSERT };
                result = CatalogueBase.SaveData(arg, ds);
            }

            if (result == "0")
            {
                ClearForm();
                MessageBox.Show(temp.STATUS_INSERT_SUCCESS, this.Text);
            }
            else
                MessageBox.Show(HandleException.HandleSQLException(result), this.Text);
        }

        private void ClearForm()
        {
            txtCode.Text = string.Empty;
            cmbTable.EditValue = DBNull.Value;
            dt.Clear();
        }

        public override void fncEdit()
        {
            
        }

        public override void fncDelete()
        {
            
        }

        public override void fncRefresh()
        {
            
        }

        public override void fncPrint()
        {
            
        }

        #endregion

        #region Support Methods

        private void btnGetNextNumber_Click(object sender, EventArgs e)
        {
            txtCode.Text = AutoConfigCode.GetNextNumber(AutoNumberCode.IVC.ToString());
            btnGetNextNumber.Enabled = false;
        }

        #endregion

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gridView1.RowCount > 0)
            {
                int num = gridView1.SelectedRowsCount;
                if (MessageBox.Show("Bạn muốn xóa " + num.ToString() + " dòng đã chọn?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    for (int i = 0; i < gridView1.SelectedRowsCount; i++)
                    {
                        if (gridView1.GetSelectedRows()[i] >= 0)
                        {
                            string code = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[i], "ItemCode").ToString();
                            for (int j = dt.Rows.Count - 1; j >= 0; j--)
                            {
                                if (dt.Rows[j]["ItemCode"].ToString() == code)
                                {
                                    dt.Rows.RemoveAt(j);
                                    i--;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
